import React, { useState, useEffect, useRef } from 'react';
import axios from 'axios';
import { Input, Button, message } from "antd";
import { SearchOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';  // 添加这行

function Layout() {
    const navigate = useNavigate();
    let box = useRef()
    const [isPaid, setIsPaid] = useState(() => {
        // 从 localStorage 读取支付状态
        return localStorage.getItem('paymentStatus') === 'completed';
    });
    const [isLoading, setIsLoading] = useState(true);
    
    useEffect(() => {
        const checkPaymentStatus = async () => {
            const urlParams = new URLSearchParams(window.location.search);
            const tradeStatus = urlParams.get('trade_status');
            const outTradeNo = urlParams.get('out_trade_no');
            
            if (tradeStatus === 'TRADE_SUCCESS' || tradeStatus === 'TRADE_FINISHED') {
                try {
                    // 向后端验证支付状态
                    const response = await axios.get(`/alipay/check/${outTradeNo}`, {
                        baseURL: 'http://localhost:3111'
                    });
                    
                    if (response.data.success) {
                        setIsPaid(true);
                        localStorage.setItem('paymentStatus', 'completed');
                        message.success('支付成功！');
                        navigate('/attdetail', { replace: true });
                    }
                } catch (error) {
                    console.error('验证支付状态失败:', error);
                }
            }
            setIsLoading(false);
        };
    
        checkPaymentStatus();
    }, [navigate]);

    // 如果正在加载，返回 null 或加载指示器
    if (isLoading) {
        return null; // 或者返回一个加载动画组件
    }

    return (
        <div className='box1'>
            <div ref={box}></div>
            <Button 
                disabled={isPaid}
                style={{
                    backgroundColor: isPaid ? '#d9d9d9' : '#1890ff',
                    color: 'white',
                    borderRadius: '8px',
                    padding: '8px 24px',
                    fontSize: '13px',
                    fontWeight: '500',
                    border: 'none',
                    boxShadow: '0 2px 4px rgba(24, 144, 255, 0.2)',
                    transition: 'all 0.3s',
                    cursor: 'pointer',
                    marginLeft: '120px',
                    marginTop:'-8px',
                    ':hover': {
                        backgroundColor: '#40a9ff',
                        transform: 'translateY(-1px)',
                        boxShadow: '0 4px 8px rgba(24, 144, 255, 0.3)'
                    }
                }} 
                onClick={async () => {
                    try {
                        if (localStorage.getItem('paymentStatus') === 'completed') {
                            message.info('您已完成支付');
                            return;
                        }
                        
                        const outTradeNo = Date.now().toString();
                        let result = await axios.post('/alipay/pay', {
                            outTradeNo,
                            subject: "迟到罚款",
                            totalAmount: '50.00',
                            returnUrl: `${window.location.origin}/attdetail?paymentStatus=completed&out_trade_no=${outTradeNo}`
                        }, {
                            baseURL: 'http://localhost:3111',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            timeout: 5000
                        })
                        
                        if (result.data.success && result.data.payUrl) {
                            const tempDiv = document.createElement('div')
                            tempDiv.innerHTML = result.data.payUrl
                            document.body.appendChild(tempDiv)
                            const form = tempDiv.querySelector('form')
                            if (form) {
                                // 移除这里的 setIsPaid，让回调处理支付状态
                                // setIsPaid(true);
                                form.submit()
                                setTimeout(() => {
                                    document.body.removeChild(tempDiv)
                                }, 100)
                            }
                        }
                    } catch (error) {
                        console.error('支付请求错误:', error);
                        if (error.code === 'ERR_NETWORK') {
                            message.error('无法连接到服务器，请确认服务器是否启动');
                        } else {
                            message.error('支付请求失败，请稍后重试');
                        }
                        setIsPaid(false);
                    }
                }}
            >
                {isPaid ? '已支付' : '立即支付'}
            </Button>
        </div>
    );
}

export default Layout;